package drds.data_propagate.driver.packets.client.command_packet;

import drds.data_propagate.driver.packets.CommandPacket;
import drds.data_propagate.driver.packets.GtidSet;
import drds.data_propagate.driver.utils.ByteHelper;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by hiwjd on 2018/4/24. hiwjd0@gmail.com
 * https://dev.mysql.com/doc/internals/en/com-binlog-dump-gtid.html
 */
public class BinlogDumpGtidPacket extends CommandPacket {

    public static final int BINLOG_DUMP_NON_BLOCK = 0x01;
    public static final int BINLOG_THROUGH_POSITION = 0x02;
    public static final int BINLOG_THROUGH_GTID = 0x04;
    @Setter
    @Getter
    public long slaveServerId;
    @Setter
    @Getter
    public GtidSet gtidSet;

    public BinlogDumpGtidPacket() {
        setCommand((byte) 0x1e);
    }


    public void decode(byte[] bytes) throws IOException {
    }


    public byte[] encode() throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        // 0. [1] write command number
        byteArrayOutputStream.write(getCommand());
        // 1. [2] flags
        ByteHelper.writeUnsignedShortLittleEndian(BINLOG_THROUGH_GTID, byteArrayOutputStream);
        // 2. [4] server-id
        ByteHelper.writeUnsignedIntLittleEndian(slaveServerId, byteArrayOutputStream);
        // 3. [4] protogenesis-filename-len
        ByteHelper.writeUnsignedIntLittleEndian(0, byteArrayOutputStream);
        // 4. [] protogenesis-filename
        // skip
        // 5. [8] protogenesis-pos
        ByteHelper.writeUnsignedInt64LittleEndian(4, byteArrayOutputStream);
        // if flags & BINLOG_THROUGH_GTID {
        byte[] bs = gtidSet.encode();
        // 6. [4] data-size
        ByteHelper.writeUnsignedIntLittleEndian(bs.length, byteArrayOutputStream);
        // 7, [] data
        // [8] n_sids // 文档写的是4个字节，其实是8个字节
        // for n_sids {
        // [16] sid
        // [8] n_intervals
        // for n_intervals {
        // [8] start (signed)
        // [8] end (signed)
        // }
        // }
        byteArrayOutputStream.write(bs);
        // }

        return byteArrayOutputStream.toByteArray();
    }
}
